<?php
namespace app\agent\controller;
use think\Controller;
use think\Db;
use think\request;
use app\common\controller\PaylogBaseController;
use app\common\controller\AgentBaseController;

class Activet extends AgentBaseController
{
	//鼓励金营销
	public function integral_marketing()
    {
    	$agentid = session('agent_id');
    	$list = Db::table('info_agent')->where('id',$agentid)->find();
    	$list['score'] 	 = substr($list['score'],0,strlen($list['score'])-2);
        $this->assign('list',$list);
        
        if($_POST){
        	$data['ad_score']=$_POST['ad_score'];
            $data['zs_score']=$_POST['zs_score'];
            $result=Db::table('info_agent')->where('id',$agentid)->update($data);;
            if($result){
				return json(['code'=>200,'msg'=>'成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'失败']);
	        }
        }
    	return $this->fetch();
    }
    public function integral_marketing_up()
    {
        $agentid = session('agent_id');
    	$data['is_score']=input('scoreid');
        $result=Db::table('info_agent')->where('id',$agentid)->update($data);
        if($result){
			return json(['code'=>200,'msg'=>'成功']);
        }else{
       		return json(['code'=>402,'msg'=>'失败']);
        }
    }
    //联盟商圈已加入
	public function union_circle1()
    {
    	$agent_id = session('agent_id');
    	$agent_info = db('info_agent')->where('id',$agent_id)->find();
    	$agent_info['ad_money'] 	 = substr($agent_info['ad_money'],0,strlen($agent_info['ad_money'])-2);
    	$this->assign('agent_info',$agent_info);
    	
    	$where['b.state'] = 2;
    	$where['b.is_state'] = 1;
    	$where['a.agent_id'] = $agent_info['id'];
    	 
    	$list = db('union_member')
				->alias('a')
				->field('a.id as member_id,a.union_id,a.lm_name,a.add_time,sum(a.customer_volume) as customer_volume,a.state,b.id,b.add_time,b.sq_name,b.tel')
				->join('union_agent b','a.union_id = b.id')
				->where($where)
				->group('union_id')
				->order('b.add_time desc')
				->paginate(20);
		$total_ads  = 0.2;
		foreach($list as $kye=>$value){
			if($value['state'] == 1){
				$total_ads = bcadd(0.02, $total_ads, 2);
			}
		}
		
		$this->assign('total_ads',$total_ads);
        $this->assign('list',$list);
    	$this->assign('empty','<span class="empty">没有数据</span>');
		
    	return $this->fetch();
    }
    
    //联盟商圈未加入,需要优化
    public function union_circle2()
    {
	  if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['store_name']))$where['a.name'] = ['like','%'.$param['store_name'].'%'];
    	}
    	
    	$where['a.state'] = 2;
    	$where['a.is_state'] = 1;
    	$list = Db::table('union_agent')
    			->where('a.id','not in',function($query){
    				$union_agent_where['agent_id'] 	= session('agent_id');
    				$union_agent_where['state'] 	= ['in','1,2'];
		    		$query->table('union_member')->where($union_agent_where)->field('union_id');
				})
				->alias('a')
				->field('a.id as id,a.name as name,a.sq_name as sq_name,a.tel as tel,sum(b.customer_volume) as customer_volume')
				->join('union_member b','a.id = b.union_id')
				->where($where)
		    	->order('a.add_time desc')
		    	->group('b.union_id')
		    	->paginate(20);
        $this->assign('list',$list);
        $this->assign('empty','<span class="empty">没有数据</span>');
		
    	return $this->fetch();
    }
    //联盟加入成员
	public function union_join()
    {
    	if(request()->isPost()){
    		$union=Db::table('union_agent')->where('id',input('lid'))->find();
    		$agent=Db::table('info_agent')->where('id',session('agent_id'))->find();
    		$param['u_id']				= $union['u_id'];
    		$param['union_id']			= input('lid');
    		$param['agent_id']			= session('agent_id');
    		$param['store_name']		= $agent['agent_name'];
    		$param['thumb']				= $agent['logo'];
    		$param['lm_name']			= $union['name'];
    		$param['store_tel']			= $agent['mobile'];
    		$param['address']			= $agent['address'];
    		$param['customer_volume']	= input('customer_volume');
    		$param['unnion_ads_money']	= 0.2;
    		$param['add_time']			= now_time();
    		$res = Db::table('union_member')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'失败']);
			}
    		
    	}
    	$this->assign('lid',input('lid'));
    	return $this->fetch();
    }
    
    
    //退出联盟
    public function union_tuichu()
    {
    	$result = db('union_member')->where('id',input('id'))->delete();
    	if($result){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    //联盟成员
	public function union_member()
    {
    	$list=Db::table('union_member')
    				->where('union_id',input('union_id'))
    				->select();
    	$this->assign('list',$list);
    	return $this->fetch();
    }
    //联盟商圈使用帮助
	public function help1()
    {
    	return $this->fetch();
    }
    //鼓励金使用帮助
    public function help2()
    {
    	return $this->fetch();
    }
    
    //红包活动	
	public function gold_active(){	
		$where['agent_id'] = session('agent_id');
		$where['state'] = 1;
		$list=db("agent_activegold")->where($where)->order('add_time desc')->paginate(20);
		$this->assign('list',$list);
		return $this->fetch();
	}
	//添加红包
	public function gold_add()
    {
    	if(request()->isPost()){
			$param['agent_id'] 	= session("agent_id");
			$param['user_id'] 	= session("agent_user_id");
			$param['user_num'] 	= input("user_num");
			$param['gold_sum'] 	= input("gold_sum");
			$param['type'] 		= input("type");
			$param['hb_type'] 	= input("hb_type");
			$param['add_time'] 	= now_time();
			$param['end_time'] 	= date('Y-m-d H:i:s',strtotime('+1 day'));
			$param['memo'] 		= input('memo')?input('memo'):'恭喜发财 大吉大利';
			
			$agent_info=db("info_agent")->where('id',session("agent_id"))->find();
			if($agent_info['score']<$param['gold_sum']){
				return json(['code'=>402,'msg'=>'商家鼓励金不足，无法创建']);
			}
			
			$res = db('agent_activegold')->insert($param);
			if($res){
				//扣除商家鼓励金
				$rest1 = db('info_agent')->where('id', session("agent_id"))->setDec('score', $param['gold_sum']);

				$paylog = new PaylogBaseController();
				//商家鼓励金记录 	
				$rest2 = $paylog->agent_score_log(session("agent_id"),10,-$param['gold_sum'],"创建红包活动扣除:".$param['gold_sum'],0,0);
				return json(['code'=>200,'msg'=>'创建成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'创建失败']);
			}
    	}
    	return $this->fetch();
    }

 	public function gold_zj()
    {
    	if(request()->isPost()){
    		$goldinfo=db('agent_activegold')->where('id',input("id"))->find();
			$param['user_num'] 	= ['exp',"user_num+".input("user_num")];
			$param['gold_sum'] 	= ['exp',"gold_sum+".input("gold_sum")];
			$param['memo'] 		= input("memo");
			$param['status'] 	= 1;
			$agent_info=db("info_agent")->where('id',session("agent_id"))->find();
			if($agent_info['score']<input("gold_sum")){
				return json(['code'=>402,'msg'=>'商家鼓励金不足，无法创建']);
			}

			$res = db('agent_activegold')->where('id',input("id"))->update($param);
			if($res){
				//扣除商家鼓励金
				$rest1 = db('info_agent')->where('id', session("agent_id"))->setDec('score', input('gold_sum'));

				$paylog = new PaylogBaseController();
				//商家鼓励金记录 	
				$rest2 = $paylog->agent_score_log(session("agent_id"),10,-input('gold_sum'),"追加".input("id")."红包活动扣除:".input('gold_sum'),0,0);
			
				return json(['code'=>200,'msg'=>'追加成功']);
			}else{
				return json(['code'=>402,'msg'=>'追加失败']);
			}
    	}
		$data=db('agent_activegold')->where('id',input("gold_id"))->find();
		$this->assign('data',$data);
    	return $this->fetch();
    }

	//红包详情	
	public function gold_info(){	
		$where['agent_id'] = session('agent_id');
		$where['id'] = input("gold_id");
		$where['state'] = 1;
		$list=db("agent_activegold")->where($where)->find();
		$this->assign('data',$list);
		return $this->fetch();
	}
	//删除红包
	public function gold_del(){
		if(request()->isAjax()){
			//修改红包信息，删除逻辑
			$res = db('agent_activegold')->where('id',input('id'))->update(['state' => 2]);
			if($res){
				return json(['code'=>200,'msg'=>'删除成功']);
			}else{
				return json(['code'=>402,'msg'=>'删除失败']);
			}
    	}
	}
    	public function gold_close(){
			Db::startTrans();
			$hb=db('agent_activegold')->where('id',input('id'))->find();
			$result=true;
			$belive_sum=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
			if($belive_sum>0){
				//返回商家鼓励金
				$rest1 = db('info_agent')->where('id', session("agent_id"))->setInc('score', $belive_sum);
				//商家鼓励金记录 	
				$rest2 =agent_score_change(session("agent_id"),11,0,0,$belive_sum,'关闭红包退回未被领取的红包');
				if($rest1&&$rest2){
					
				}else{
					$result=FALSE;
				}
			}
			$up['state']=2;
			$up['user_num']=0;
			$up['gold_sum']=0;
			$up['peoples']=0;
			$up['sums']=0;
			$rest3=db('agent_activegold')->where('id',input('id'))->update($up);
			$rest4=db('agent_activelog')->where('gold_id',input('id'))->update(['state'=>2]);
			if(!$rest3){
				$result=FALSE;
			}
			if($result){
				Db::commit();
				return json(['code'=>200,'msg'=>'关闭成功']);
			}else{
				Db::rollback();
				return json(['code'=>402,'msg'=>'关闭失败']);
			}
	}
    
	//红包改变状态
	public function gold_status()
    {
    	$where['status'] = input('status');
    	$ress = db('agent_activegold')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>402,'msg'=>'操作失败']);
		}
    }
	
	//红包领取日志
	public function gold_log()
    {
    	$where['gold_id'] = input('gold_id');
		$list=db("agent_activelog")->where($where)->paginate(10);
		$this->assign('list',$list);
    	return $this->fetch();
    }
	
	//店铺扫码红包
	public function smfk()
    {
    	$agent_activegold = db('agent_activegold')->where('id',input('gold_id'))->find();
    	$agent_info = db('info_agent')->where('id',$agent_activegold['agent_id'])->find();
		
		//二维码链接
    	$code_url=config('API_DOMAIN')."agent/activet/hongb03?m=".$agent_activegold['id'];
    	
    	$agent_info['code_url'] = $code_url;
    	
    	$this->assign('agent_info',$agent_info);    	
		$this->assign('hb',$agent_activegold);		
		$this->assign('gold_id',$agent_activegold['id']);
    	
    	return $this->fetch();
    }
	
	//店铺新用户红包
	public function xsmfk()
    {
    	$agent_activegold = db('agent_activegold')->where('id',input('gold_id'))->find();
		$agent_info = db('info_agent')->where('id',$agent_activegold['agent_id'])->find();
		
		//二维码链接
    	$code_url=config('API_DOMAIN')."agent/activet/hongb03?m=".$agent_activegold['id'];
    	
    	$agent_info['code_url'] = $code_url;
    	
    	$this->assign('agent_info',$agent_info);  	
		$this->assign('hb',$agent_activegold);	
		$this->assign('gold_id',$agent_activegold['id']);
    	
    	return $this->fetch();
    }
	
		//红包开页面
	public function hongb03(){
		$hb=db("agent_activegold")->where("id",input("m"))->find();
		if(!$hb){
			echo '访问错误';
			exit;
		}
		$type=get_brower_type();//判断是微信还是支付宝打开
		$redirect=config('API_DOMAIN')."agent/activet/hongb03?m=".input("m");
		$openid=session("openid");
		if(!$openid){
			if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else{
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}
		}
		if($type==1){//支付宝openid
			$field="alipay_id";
			$pay_type=3;
			if(!$openid){
				$openid=user_ali_id($auth_code);
			}
		}elseif($type==2){//微信openid
			$field="openid";
			$pay_type=2;
			if(!$openid){
				$openid=user_wx_id($auth_code);
			}
		}	
		session('openid',$openid);
		$send_user=db("info_user")->find($hb['user_id']);
		if($openid){
			$w_u[$field]=$openid;
			$user=db('info_user')->where($w_u)->find();
			if(!$user){
				$data[$field]			= $openid;
				$data['level']			= $send_user['id'];
				$data['agency_id1']		= $send_user['agency_id1'];
				$data['agency_id2']		= $send_user['agency_id2'];
				$data['oem_id']			= 1;
				$data['salesman_id']	= $send_user['salesman_id'];
				$data['tj_agent']		= $send_user['tj_agent'];
				$data['tj_pt']			= $send_user['tj_pt'];
				$data['add_time']		= now_time();
				$user_id=Db::name('info_user')->insertGetId($data);
				$this->assign('flag',2);
			}else{
				$user_id=$user['id'];
				//1 已注册 2 未注册  
				$this->assign('flag',1);
				$list=db("agent_activelog")->where("gold_id",input("m"))->select();
				if($list){//判断我是否已经领取过
					foreach($list as $k){
						if($k['user_id']==$user_id){
							$this->assign('flag',3);//已领取过
							break;
						}
					}
				}	
			}			
		}
		$user=db("info_user")->where("id",$user_id)->find();
		session("info_user",$user);
		$this->assign('user',$send_user);
		$agent=db("info_agent")->field("agent_name")->find($hb['agent_id']);
		$this->assign('agent',$agent);
		$this->assign('hb',$hb);
		return $this->fetch();
	}

	public function hongb_gq(){
		return $this->fetch();
	}
	
	//红包领取页面
	public function hongb_page(){
		header("Content-type: text/html; charset=utf-8"); 
		Db::startTrans();
		$hb_id=input('m');
		$user_id=session('info_user')['id'];
		$hb=db("agent_activegold")->alias("a")->lock(true)->
		join("info_agent b","a.agent_id=b.id")->field("a.*,b.agent_name,b.logo")->
		where("a.id",$hb_id)->find();
		$message="";
		$count=0;//当前领取人数
		$status=1;//红包状态
		if(!$hb||$hb['state']==2){
			$message= '红包已领完或者已关闭';
			$status=0;
		}
		if($hb['peoples']>=$hb['user_num']){
			$message="红包已领完或者已关闭";
			$status=0;
		}
		$gold_num=0;//我领取的
		$wh['state']=1;
		$wh['gold_id']=$hb_id;
		$list=db("agent_activelog")->where($wh)->order("add_time desc")->limit($hb['user_num'])->select();
		if($list){//判断我是否已经领取过
			foreach($list as $k){
				if($k['user_id']==$user_id){
					$status=0;
					$gold_num=$k['gold_num'];
					break;
				}
			}
		}
		if($status==1){
			$result=true;
			$belive_sum=$hb['gold_sum']-$hb['sums'];
			if($belive_sum<0){
				$message="红包已领完或者已关闭";
				$result=FALSE;
			}
			//平均红包
			if($hb['hb_type']==1){
				if($hb['user_num']-$hb['peoples']==1){
					$gold_num=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
				}else{
					//当前剩余的红包
					$belive_sum=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
					//当前剩余的人数
					$p=$hb['user_num']-$hb['peoples'];
					$gold_num=sprintf("%.2f",$belive_sum/$p);
				}
				
			}else{
				//如果是最后一个红包用红包总金额减去已经领取的
				if($hb['user_num']-$hb['peoples']==1){
					$up['status']=2;	
					$gold_num=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
				}else{
					$p=$hb['user_num']-$hb['peoples'];
					//当前剩余的
					$belive_sum=sprintf("%.2f",$hb['gold_sum']-$hb['sums']);
					$max=sprintf("%.2f",$belive_sum/$p*2*10000);
					$gold_num=sprintf("%.2f",rand(1,$max)/10000);
					if($gold_num>=$belive_sum||$gold_num==0){
						$gold_num = sprintf("%.2f",$belive_sum/$p*100000/100000);
					}
				}
			}
			$up['peoples']=['exp',"peoples+1"];
			$up['sums']=['exp',"sums+$gold_num"];
			$res=db("agent_activegold")->where("id",$hb_id)->update($up);
			if($res){
				$res=db("info_user")->where("id",$user_id)->setInc('score',$gold_num);
				if($res){
					$res=user_score_change($user_id,12,$gold_num,
					'领取鼓励金红包',0,0);
					if(!$res){
						$result=FALSE;
					}
				}else{
					$result=FALSE;
				}
			}else{
				$result=FALSE;
			}
			
			$res=$this->add_hblog($hb['id'],session("info_user")['id'],session("info_user")['mobile'],$gold_num,session("info_user")['user_name'],session("info_user")['logo']);
			if(!$res){
				$result=FALSE;
			}
		}else{
			$result=false;
		}
		$this->assign('gold_num',$gold_num);
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		
		$listlog=db("agent_activelog")->where($wh)->order("add_time desc")->paginate($hb['peoples']);
		$this->assign('hb',$hb);
		$this->assign('list',$listlog);
		$this->assign('count',$hb['peoples']);
		$this->assign('status',$status);
		$this->assign('message',$message);
		return $this->fetch();
	}
	public function add_hblog($gold_id,$user_id,$mobile,$gold_num,$user_name,$logo){
		$type=get_brower_type();
		if($user_name){
			
		}else{
			if($type==1){
			  $user_name='支付宝会员';
			}else{
			  $user_name='微信会员';
			}
		}	
		$data['gold_id']=$gold_id;
		$data['user_id']=$user_id;
		$data['mobile']=$mobile;
		$data['gold_num']=$gold_num;
		$data['user_name']=$user_name;
		$data['logo']=$logo?$logo:"/public/static/index/images/member.jpg";
		$data['add_time']=now_time();
		$res=db("agent_activelog")->insert($data);
		return $res;
	}
}
